/*
 * Created on Jan 10, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.scohen.juploadr.upload;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.Protocol;
import org.scohen.juploadr.prefs.Configuration;

/**
 * @author steve
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class HttpClientFactory {

    public static HttpClient getHttpClient() {
        HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
        Configuration config = Configuration.getInstance();
        Protocol http;
        if (config.isThrottlingEnabled()) {
            http = new Protocol("http", new BandwidthLimitingProtocolSocketFactory(), 80);
        } else {
            http = new Protocol("http", new DefaultProtocolSocketFactory(), 80);
        }

        Protocol.registerProtocol("http", http);

        if (config.isProxyEnabled()) {
            HostConfiguration hc = client.getHostConfiguration();
            String proxyHost = config.getProxyHost();
            String proxyPassword = config.getProxyPassword();
            String proxyUsername = config.getProxyUsername();
            int proxyPort = config.getProxyPort();
            hc.setProxy(proxyHost, proxyPort);

            if (proxyUsername.length() > 0) {

                Credentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
                client.getParams().setAuthenticationPreemptive(true);
                AuthScope scope = new AuthScope(proxyHost, proxyPort);
                client.getState().setProxyCredentials(scope, creds);
            }
        }
        client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
        client.getHttpConnectionManager().getParams().setSoTimeout(60000);
        client.getParams().setParameter(HttpClientParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(0, false));
        return client;
    }
}